<?php

namespace app\api\controller\user;

use app\api\model\user\UserAddress;
use app\api\controller\Controller;
use app\common\model\settings\Region as RegionModel;

/**
 * 收货地址控制器
 */
class Address extends Controller
{
    /**
     * 收货地址列表
     */
    public function lists()
    {
        $user = $this->getUser();
        $model = new UserAddress;
        $list = $model->getList($user['user_id'],true);
        return $this->renderSuccess('', [
            'list' => $list,
            'default_id' => $user['address_id'],
        ]);
    }

    public function getUserAddressLists()
    {

        $user = $this->getUser();
        $lng = $this->request->param('lng')??0; //经度
        $lat = $this->request->param('lat')??0; //纬度

        $model = new UserAddress;
        $list = $model->getList($user['user_id']);
        $array = [];
        if($list){
            foreach ($list as $key => $value){
                // 使用示例
                $point1 = array($lat, $lng); //当前定位的经纬度
                $point2 = array($value['latitude'],$value['longitude']); //用户地址的经纬度
                $distance = getDistanceBetweenPoints($point1, $point2, 'km'); // 距离以公里为单位
                if($distance > 0.2){
                    $array[] = $value;
                }
            }
        }

        return $this->renderSuccess('', [
            'list' => $array,
        ]);
    }

    /**
     * 添加收货地址
     */
    public function add()
    {
        $data = $this->request->post();
        if (!isPhoneNumber($data['phone'])) {
            return $this->renderError('手机号格式不正确');
        }
        if ($data['name'] == '') {
            return $this->renderError('收货人不能为空');
        }
        if ($data['detail'] == '') {
            return $this->renderError('收货地址不能为空');
        }
        $model = new UserAddress;
        if ($model->add($this->getUser(), $data)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError('添加失败');
    }

    /**
     * 收货地址详情
     */
    public function detail($address_id)
    {
        $user = $this->getUser();
        $detail = UserAddress::detail($user, $address_id);
        $region = $detail['region']? array_values($detail['region']):[];
        $regionData = RegionModel::getRegionForApi();
        return $this->renderSuccess('', compact('detail', 'region', 'regionData'));
    }

    /**
     * 编辑收货地址
     */
    public function edit($address_id)
    {
        $user = $this->getUser();
        $model = UserAddress::detail($user, $address_id);

        $data = $this->request->post();
        if (!isPhoneNumber($data['phone'])) {
            return $this->renderError('手机号格式不正确');
        }

        if ($model->edit($this->request->post())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError('更新失败');
    }

    /**
     * 设为默认地址
     */
    public function setDefault($address_id)
    {
        $user = $this->getUser();
        $model = UserAddress::detail($user, $address_id);
        if ($model->setDefault($user)) {
            return $this->renderSuccess('设置成功');
        }
        return $this->renderError('设置失败');
    }

    /**
     * 删除收货地址
     */
    public function delete($address_id)
    {
        $user = $this->getUser();
        $model = UserAddress::detail($user, $address_id);
        if ($model->remove($user)) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError('删除失败');
    }


    /**
     * 获取用户地址中距离最近的一条
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     * @Author joey
     * @date 2024/3/15 15:14
     */
    public function minDistanceAddress()
    {
        $user = $this->getUser();
        $where['longitude'] = $this->request->param('lng');
        $where['latitude'] = $this->request->param('lat');
        $where['city_id'] = $this->request->param('city_id') ?: 0;
        if (!isset($where['longitude']) || !isset($where['latitude']) || !$user['user_id']) {
            return $this->renderError('', ['address' => '']);
        }
        $model = new UserAddress;
        $list = $model->getMinDistance($where, $user['user_id']);
        if ($list) {
            foreach ($list as &$item) {
                $item['region']['province'] = RegionModel::getNameById($item['province_id']);
                $item['region']['city'] = RegionModel::getNameById($item['city_id']);
                $item['region']['region'] = $item['region_id'] == 0 ? '' : RegionModel::getNameById($item['region_id']);
            }
            unset($item);
        }
        return $this->renderSuccess('', [
            'address' => $list[0] ?? '',
        ]);
    }

}